package core

import (
	"errors"
	"fmt"
	"log/slog"
	"logengine/model"
	"strconv"
	"strings"
	"time"

	"github.com/go-resty/resty/v2"
)

func Work(dataStr string) error {
	// dataJson := []byte(fmt.Sprintf("%d,%d,%d,%d,%s", rect.Left, rect.Top, rect.Right, rect.Bottom, winText))
	// 744,729,784,743,16
	// dataJson rect.Left, rect.Top, rect.Right, rect.Bottom, winText))

	arr := strings.Split(dataStr, ",")
	if len(arr) < 4 {
		return errors.New("len error < 4")
	}

	left, _ := strconv.Atoi(arr[0])
	top, _ := strconv.Atoi(arr[1])
	// right := arr[2]
	// bottom := arr[3]
	winText := arr[4]
	//
	datas := make([]model.Report, 0, 1)
	//
	dataAddr := GetDataAddr(left, top)
	if len(dataAddr) == 0 {
		return nil
	}

	datas = append(datas, model.Report{
		DataAddr: dataAddr,
		Result:   winText,
	})
	msgData := new(model.MessageData)
	msgData.Datas = datas
	// http post
	PostMsg(msgData, "ocr")
	return nil
}

func WorkArray(strArr []string) error {
	datas := make([]model.Report, 0, len(strArr))
	//
	for _, dataStr := range strArr {
		arr := strings.Split(dataStr, ",")
		if len(arr) < 4 {
			continue
		}
		left, _ := strconv.Atoi(arr[0])
		top, _ := strconv.Atoi(arr[1])
		winText := arr[4]
		//
		dataAddr := GetDataAddr(left, top)
		if len(dataAddr) == 0 {
			continue
		}
		//
		datas = append(datas, model.Report{
			DataAddr: dataAddr,
			Result:   winText,
		})
	}
	slog.Warn("collect", "data count", len(datas))
	msgData := new(model.MessageData)
	msgData.Datas = datas
	// http post
	PostMsg(msgData, "ocr")
	return nil
}

func PostMsg(model interface{}, collectType string) {
	// "127.0.0.1:8006"
	endPoint := fmt.Sprintf("http://%s%s", "127.0.0.1:8006", "/v1/recmsg")
	//
	resp, err := restyClient.R().
		SetHeader("collect-type", collectType).
		SetBody(model).Post(endPoint)
	if err != nil {
		slog.Error(err.Error())
	}
	_ = resp.RawBody().Close()
}

var restyClient *resty.Client

func init() {
	initResty()
}

func initResty() {
	restyClient = resty.New()
	restyClient.SetRetryCount(3)
	restyClient.SetRetryMaxWaitTime(3 * time.Second)
}
